package cn.nexttec.noteplayer.ui.widget.image_editor

import android.content.Context
import android.graphics.*
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.*
import android.widget.*
import androidx.appcompat.app.AlertDialog
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.databinding.LayoutImageViewerBinding
import cn.nexttec.noteplayer.ui.widget.PopupDialog
import com.bumptech.glide.Glide
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import kotlin.math.min

class ImageEditorView @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null
) : FrameLayout(context, attrs), CutOverlayView.CutListener {

    private val binding: LayoutImageViewerBinding = LayoutImageViewerBinding.inflate(LayoutInflater.from(context), this, true)

    private val imageView: ImageView = binding.iamgeView
    private val cutOverlayView: CutOverlayView = CutOverlayView(context)
    private val drawingView: DrawingView = DrawingView(context)

    private var isCutMode = false
    private var isDrawing = false
    private var zoomScale = 1f
    private var paintColor = Color.BLACK

    private var lastTouchX = 0f
    private var lastTouchY = 0f
    private var isDragging = false

    interface OnImageSavedListener {
        fun onImageSaved(result: Bitmap)
    }

    private var onImageSavedListener: OnImageSavedListener? = null

    fun setOnImageSavedListener(listener: OnImageSavedListener) {
        this.onImageSavedListener = listener
    }

    init {
        cutOverlayView.setCutListener(this@ImageEditorView)
        drawingView.performSaveCallback = {
            binding.bottomToolBar.visibility = View.VISIBLE
        }

        drawingView.performExitCallback = {
            binding.bottomToolBar.visibility = View.VISIBLE
        }

        drawingView.onDrawingSavedCallback = {
            applyDrawingToImage()
        }

        addView(cutOverlayView)
        addView(drawingView)

        setupControls()
    }

    private fun setupControls() {
        binding.ivCut.setOnClickListener {
            isCutMode = true
            cutOverlayView.enableCutMode(true)
        }

        binding.spZoom.apply {
            adapter = CustomSpinnerAdapter(context, listOf("1x", "1.25x", "2x", "3x", "5x"))
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>?, view: View?, pos: Int, id: Long) {
                    zoomScale = when (pos) {
                        1 -> 1.25f
                        2 -> 2f
                        3 -> 3f
                        4 -> 5f
                        else -> 1f
                    }
                    applyZoom()
                    resetImagePosition()
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {}
            }
        }

        binding.btnSave.setOnClickListener {
            saveEditedImage()
        }

        binding.ivPen.setOnClickListener {
            isDrawing = true
            drawingView.enableDrawing(true)
            binding.bottomToolBar.visibility = View.GONE
        }
    }

    private fun applyZoom() {
        imageView.scaleX = zoomScale
        imageView.scaleY = zoomScale
    }

    private fun resetImagePosition() {
        imageView.translationX = 0f
        imageView.translationY = 0f
    }

    fun applyDrawingToImage() {
        val originalBitmap = getCurrentBitmap()

        // 创建新的合成图像（注意用 ImageView 的尺寸）
        val combinedBitmap = Bitmap.createBitmap(imageView.width, imageView.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(combinedBitmap)

        // 先绘制当前 ImageView 显示的图像
        imageView.draw(canvas)

        // 再绘制当前 DrawingView 的内容
        drawingView.drawToCanvas(canvas)

        // 更新 ImageView 显示内容
        imageView.setImageBitmap(combinedBitmap)

        // 清空绘图
        drawingView.clearDrawing()
    }

    private fun saveEditedImage() {
        // 退出绘图模式
        isDrawing = false
        drawingView.enableDrawing(false)

        // 获取最终合成图像
        val resultBitmap = getCurrentBitmap()

        // 回调出去
        onImageSavedListener?.onImageSaved(resultBitmap)
    }

    fun setImage(inputStream: InputStream) {
        Glide.with(context).load(inputStream.readBytes())
            .into(imageView)
    }

    override fun onCutConfirmed(cutRect: RectF) {
        val bitmap = getCurrentBitmap()
        val scaledRect = Rect(
            cutRect.left.toInt(),
            cutRect.top.toInt(),
            cutRect.right.toInt(),
            cutRect.bottom.toInt()
        ).apply {
            right = min(right, bitmap.width)
            bottom = min(bottom, bitmap.height)
        }

        val cropped = Bitmap.createBitmap(bitmap, scaledRect.left, scaledRect.top, scaledRect.width(), scaledRect.height())
        imageView.setImageBitmap(cropped)
        cutOverlayView.enableCutMode(false)
        resetImagePosition()
    }

    private fun getCurrentBitmap(): Bitmap {
        val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        imageView.draw(canvas)
        drawingView.draw(canvas)
        return result
    }

    private fun getImageBounds(): RectF {
        val drawable = imageView.drawable ?: return RectF(0f, 0f, 0f, 0f)
        val intrinsicWidth = drawable.intrinsicWidth
        val intrinsicHeight = drawable.intrinsicHeight
        val scaleX = imageView.scaleX
        val scaleY = imageView.scaleY
        val width = intrinsicWidth * scaleX
        val height = intrinsicHeight * scaleY
        return RectF(0f, 0f, width, height)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (isCutMode || isDrawing) return false

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchX = event.x
                lastTouchY = event.y
                isDragging = true
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                if (isDragging && zoomScale > 1f) {
                    val dx = event.x - lastTouchX
                    val dy = event.y - lastTouchY

                    val bounds = getImageBounds()
                    val maxTransX = maxOf(0f, (width - bounds.width()) / 2f)
                    val maxTransY = maxOf(0f, (height - bounds.height()) / 2f)

                    val newTransX = imageView.translationX + dx
                    val newTransY = imageView.translationY + dy

                    imageView.translationX = newTransX.coerceIn(-bounds.width() + maxTransX, maxTransX)
                    imageView.translationY = newTransY.coerceIn(-bounds.height() + maxTransY, maxTransY)

                    lastTouchX = event.x
                    lastTouchY = event.y
                    return true
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                isDragging = false
                return true
            }
        }
        return super.onTouchEvent(event)
    }
}

class CustomSpinnerAdapter(context: Context, private val items: List<String>) :
    ArrayAdapter<String>(context, R.layout.item_scale, items) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = LayoutInflater.from(context).inflate(R.layout.item_scale, parent, false)
        val textView = view.findViewById<TextView>(android.R.id.text1)
        textView.text = items[position]
        return view
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        return getView(position, convertView, parent)
    }



}
